<template>
  <div class="app-container">
    <v-row :gutter="20">
      <v-col>
        <!-- 搜索表单 -->
        <v-form ref="queryForm" v-show="showSearch" label-width="68px">
          <v-row>
            <v-col md="3" style="padding-bottom: 2px;max-width: 250px">
              <v-text-field
                label="系统模块"
                v-model="queryParams.title"
                placeholder="请输入系统模块"
                outlined
                dense
                clearable
                hide-details="auto"
                @keyup.enter.native="handleQuery"
                style="width: 250px;"
              ></v-text-field>
              <v-select
                label="操作状态"
                v-model="queryParams.status"
                :items="statusOptions"
                item-text="dictLabel"
                item-value="dictValue"
                placeholder="操作状态"
                dense
                outlined
                clearable
                hide-details="auto"
                style="width: 160px;margin-top: 1rem"
              ></v-select>
            </v-col>
            <v-col md="3" style="padding-bottom: 2px;max-width: 250px">
              <v-text-field
                label="操作人员"
                v-model="queryParams.operName"
                placeholder="请输入操作人员"
                outlined
                dense
                hide-details="auto"
                style="width: 250px;"
                @keyup.enter.native="handleQuery"
              ></v-text-field>
              <v-menu
                ref="dateRangeMenu"
                v-model="dateRangeMenu"
                :close-on-content-click="false"
                transition="scale-transition"
                offset-y
                max-width="240px"
                min-width="auto"
                hide-details="auto"
                style="width: 240px;padding-top: 0;margin-left: -15px"
              >
                <template v-slot:activator="{ on, attrs }">
                  <v-text-field
                    v-model="date"
                    label="操作时间"
                    prepend-icon="mdi-calendar"
                    v-bind="attrs"
                    @blur="date = parseDate(dateFormatted)"
                    v-on="on"
                    clearable
                    style="width: 240px;margin-left: -12px;margin-top: 10px"
                  ></v-text-field>
                </template>
                <v-date-picker
                  v-model="date"
                  no-title
                  @input="dateRangeMenu = false"
                  style="padding: 0"
                ></v-date-picker>
              </v-menu>
            </v-col>
            <v-col md="3" style="padding-bottom: 2px;">
              <v-select
                label="操作类型"
                v-model="queryParams.businessType"
                :items="typeOptions"
                item-text="dictLabel"
                item-value="dictValue"
                placeholder="操作类型"
                dense
                outlined
                clearable
                hide-details="auto"
                style="width: 200px;"
              ></v-select>
              <p style="display: inline-block;position: absolute;margin-top: 1rem">
                <v-btn
                  small color="primary"
                  :loading="loading"
                  @click="handleQuery">
                  <v-icon left>
                    mdi-magnify
                  </v-icon>
                  搜索
                </v-btn>
                <v-btn
                  small
                  :loading="loading"
                  @click="resetQuery"
                  style="margin-left: 10px"
                >
                  <v-icon left>
                    mdi-autorenew
                  </v-icon>
                  重置
                </v-btn>
              </p>
            </v-col>
          </v-row>
        </v-form>
      </v-col>
    </v-row>

    <!-- 表格操作按钮区 -->
    <v-row style="margin-bottom: -5px;margin-top: 0;">
      <!--二次确认删除按钮 -->
      <v-col md="1" style="max-width: 84px">
        <span v-if="!showConfirmDelete">
          <v-btn color="#C62828"
                 small
                 plain
                 outlined
                 :disabled="multiple"
                 @click="onClickDelete()"
                 v-hasPermi="['system:operlog:remove']">
            <v-icon left>
              mdi-delete
            </v-icon>
            删除
          </v-btn>
        </span>
        <span v-else>
          <v-tooltip top style="z-index: 1000">
            <template v-slot:activator="{ on, attrs }">
              <v-btn
                small color="error"
                plain
                outlined
                :disabled="multiple"
                v-bind="attrs"
                v-on="on"
                @click="handleDelete()"
                v-hasPermi="['system:operlog:remove']">
                <v-icon left>
                  mdi-delete
                </v-icon>
                确定
              </v-btn>
            </template>
            <span>请再次点击确定删除</span>
          </v-tooltip>
        </span>
      </v-col>
      <v-col md="1" style="max-width: 84px">
        <span v-if="!showConfirmClean">
          <v-btn color="#C62828"
                 small
                 plain
                 outlined
                 @click="onClickClean()"
                 v-hasPermi="['system:operlog:remove']">
            <v-icon left>
              mdi-delete-variant
            </v-icon>
            清空
          </v-btn>
        </span>
        <span v-else>
          <v-tooltip top>
            <template v-slot:activator="{ on, attrs }">
              <v-btn
                small color="error"
                plain
                outlined
                v-bind="attrs"
                v-on="on"
                @click="handleClean()"
                v-hasPermi="['system:operlog:remove']">
                <v-icon left>
                  mdi-delete-variant
                </v-icon>
                确定
              </v-btn>
            </template>
            <span>请再次点击确定清空</span>
          </v-tooltip>
        </span>
      </v-col>
      <v-col md="1" style="max-width: 84px">
        <v-btn
          type="warning"
          small
          plain
          outlined
          @click="handleExport"
          v-hasPermi="['system:operlog:export']">
          <v-icon left>
            mdi-upload
          </v-icon>
          导出
        </v-btn>
      </v-col>
      <v-col style="float: right">
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </v-col>
    </v-row>

    <!-- 表格-->
    <v-main>
      <v-data-table v-if="list"
                    v-model="ids"
                    :headers="headers"
                    :items="list"
                    :items-per-page="queryParams.pageSize"
                    hide-default-footer
                    :loading="loading"
                    loading-text="加载中,请稍后.."
                    show-select
                    item-key="operId"
                    class="elevation-1"
                    no-data-text="暂无数据"
      >
        <!-- 操作类型插槽 -->
        <template v-slot:item.businessType="{ item }">
          {{ typeFormat(item) }}
        </template>

        <template v-slot:item.status="{ item }">
          {{ statusFormat(item) }}
        </template>

        <!-- 操作日期 -->
        <template v-slot:item.operTime="{ item }">
          {{ parseTime(item.operTime) }}
        </template>

        <!-- 按钮插槽 -->
        <template v-slot:item.actions="{ item, index }">
          <v-btn text
                 small
                 plain
                 height="20"
                 width="40"
                 @click="handleView(item, index)"
                 v-hasPermi="['system:operlog:query']">
            <v-icon small>
              mdi-eye
            </v-icon>
            详细
          </v-btn>
        </template>
      </v-data-table>
      <!-- 外部分页-->
      <div class="d-flex align-center justify-end text-center">
        <div class="d-flex" style="margin-top: 3px;font-size: 14px;font-weight: 400">
          <span>每页</span>
          <v-select
            v-model="queryParams.pageSize"
            :items="numbers"
            dense
            @change="getList" style="max-width: 80px;max-height: 20px;margin-top: -4px;text-align: center;">
            <template v-slot:selection="{ item, index }">
                  <span style="width: 100%">
                    {{item}}
                  </span>
            </template>
          </v-select>
          <span>条记录</span>
        </div>
        <v-pagination
          v-model="queryParams.pageNum"
          @input="getList"
          :length="queryParams.totalPages"
          :total-visible="7"
        ></v-pagination>
      </div>
    </v-main>

    <v-dialog
      v-model="open" max-width="850px" persistent>
      <v-card>
        <v-card-title>
          <span style="font-size: 16px;padding: 0;">操作日志详细</span>
        </v-card-title>
        <v-row align="center" justify="center" style="width: 100%;margin: 0 auto;">
          <v-item-group
            v-model="window"
            class="shrink mr-6"
            mandatory
            tag="v-flex"
          >
            <v-item
              v-for="(item, n) in list.length"
              :key="n"
              v-slot="{ active, toggle }"
            >
              <div>
                <v-btn
                  :input-value="active"
                  icon
                  @click="toggle"
                >
                  <v-icon>mdi-record</v-icon>
                </v-btn>
              </div>
            </v-item>
          </v-item-group>

          <v-col md="10">
            <v-window
              v-model="window"
              class="elevation-1"
              vertical
              style="max-height: 800px;overflow: auto;"
            >
              <v-window-item
                v-for="(item, n) in list"
                :key="n"
              >
                <v-card flat>
                  <v-card-text>
                    <v-row
                      align="center"
                      style="margin-bottom: 0px;"
                    >
                      <v-icon>mdi-history</v-icon>
                      <strong class="text-h6">日志编号:  {{ item.operId }}</strong>
                      <v-spacer></v-spacer>
                    </v-row>
                      <v-col md="5" style="padding: 0">
                        <v-card-text style="padding: 10px">
                          操作模块： {{ typeFormat(item) }}
                        </v-card-text>
                        <v-card-text style="padding: 10px">
                          登录信息： {{ item.operName }} / {{ item.operIp }}
                        </v-card-text>
                      </v-col>
                      <v-col md="5" style="padding: 0">
                        <v-card-text style="padding: 10px">
                          请求地址： {{ item.operUrl }}
                        </v-card-text>
                        <v-card-text style="padding: 10px">
                          请求方式： {{ item.requestMethod }}
                        </v-card-text>
                      </v-col>
                      <v-col md="10" style="padding: 0">
                        <v-card-text style="padding: 10px">
                          操作方法： {{ item.method }}
                        </v-card-text>
                      </v-col>
                      <v-col md="10" style="padding: 0">
                        <v-card-text style="padding: 10px">
                          请求参数： {{ item.operParam }}
                        </v-card-text>
                      </v-col>
                      <v-col md="10" style="padding: 0">
                        <v-card-text style="padding: 10px">
                          返回参数： {{ item.jsonResult }}
                        </v-card-text>
                      </v-col>
                      <v-col md="5" style="padding: 0">
                        <v-card-text style="padding: 10px">
                          操作状态： {{ statusFormat(item) }}
                        </v-card-text>
                        <v-card-text style="padding: 10px">
                          操作时间： {{ parseTime(item.operTime) }}
                        </v-card-text>
                      </v-col>
                      <v-col md="10" style="padding: 0" v-if="item.status === 1">
                        <v-card-text style="padding: 10px">
                          异常信息： {{ item.errorMsg }}
                        </v-card-text>
                      </v-col>
                  </v-card-text>
                </v-card>
              </v-window-item>
            </v-window>
          </v-col>
        </v-row>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn
            text
            @click="open = false">
            关闭
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
import { list, delOperlog, cleanOperlog } from "@/api/system/operlog";
import { commonUtils } from "@/utils/commonUtils";

export default {
  name: "Operlog",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 是否显示弹出层
      open: false,
      // 类型数据字典
      typeOptions: [],
      // 类型数据字典
      statusOptions: [],
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        operName: undefined,
        businessType: undefined,
        status: undefined,
        totalPages: 0, // 总页数
      },
      window: 0,
      showConfirmDelete: false,
      showConfirmClean: false,
      headers: [
        {
          text: '日志编号', value: 'operId', align: 'center', sortable: false },
        { text: '系统模块', value: 'title', sortable: false, align: 'center' },
        { text: '操作类型', value: 'businessType', sortable: false, align: 'center' },
        { text: '请求方式', value: 'requestMethod', sortable: false, align: 'center' },
        { text: '操作人员', value: 'operName', sortable: false, align: 'center' },
        { text: '主机', value: 'operIp', sortable: false, align: 'center' },
        { text: '操作状态', value: 'status', sortable: false, align: 'center' },
        { text: '操作日期', value: 'operTime', sortable: false, align: 'center' },
        { text: '操作', value: 'actions', sortable: false, align: 'center' },
      ],
      numbers: [10, 15, 20, 50, 100], // 每页条数选择
      date: null,
      dateRangeMenu: false,
      dateFormatted: commonUtils.formatDate((new Date(Date.now() - (new Date()).getTimezoneOffset() * 60000)).toISOString().substr(0, 10)),
    };
  },
  watch: {
    ids() {
      this.handleSelectionChange();
    },
    date (val) {
      this.dateFormatted = this.formatDate(this.date)
    },
  },
  created() {
    this.getList();
    this.getDicts("sys_oper_type").then(response => {
      this.typeOptions = response.data;
    });
    this.getDicts("sys_common_status").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    /** 查询登录日志 */
    getList() {
      this.loading = true;
      list(this.addDateRange(this.queryParams, this.dateRange)).then( response => {
        this.list = response.rows;
        this.total = response.total;
        // 总页数
        this.queryParams.totalPages = Math.ceil(this.total / this.queryParams.pageSize);
        this.loading = false;
      });
    },
    // 操作日志状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 操作日志类型字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.businessType);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.$refs.queryForm.reset(); // 重置
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange() {
      this.single = this.ids.length !== 1;
      this.multiple = !this.ids.length;
      this.showConfirmDelete = false;
    },
    /** 详细按钮操作 */
    handleView(row, index) {
      this.open = true;
      this.form = row;
      this.window = index;
    },
    // 表格列点击删除按钮，切换确定删除按钮
    onClickDelete() {
      this.showConfirmDelete = true;
      setTimeout(() => {
        this.showConfirmDelete = false;
      }, 4000);
    },
    /** 删除按钮操作 */
    async handleDelete() {
      this.$store.commit("snackbar/CLOSE_SNACKBAR");
      const operIds = this.ids.map(item => item.operId);
      await delOperlog(operIds).then(res => {
        if (res) {
          // 使用全局消息提示
          this.$store.dispatch('snackbar/openSnackbar', {
            msg: '删除成功',
            color: 'success'
          })
          this.getList();
        }
      });
    },
    onClickClean() {
      this.showConfirmClean = true;
      setTimeout(() => {
        this.showConfirmClean = false;
      }, 4000);
    },
    /** 清空按钮操作 */
    async handleClean() {
      this.$store.commit("snackbar/CLOSE_SNACKBAR");
      await cleanOperlog().then(res => {
        if (res) {
          // 使用全局消息提示
          this.$store.dispatch('snackbar/openSnackbar', {
            msg: '清空成功',
            color: 'success'
          })
          this.getList();
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/operlog/export', {
        ...this.queryParams
      }, `operlog_${new Date().getTime()}.xlsx`)
    },
    // 创建时间 日期格式化
    formatDate (date) {
      if (!date) return null
      const [year, month, day] = date.split('-')
      return `${month}/${day}/${year}`
    },
    parseDate (date) {
      if (!date) return null
      const [month, day, year] = date.split('/')
      return `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`
    },
  }
};
</script>

